package com.guodi.model.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.AjaxResult;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.secure.LoginUser;
import com.guodi.core.tool.api.R;
import com.guodi.model.dto.ApiIdtModelLayerDto;
import com.guodi.model.dto.IdtModelLayerDto;
import com.guodi.model.dto.LayerDto;
import com.guodi.model.entity.IdtIndicatorsDir;
import com.guodi.model.entity.IdtModelLayer;
import com.guodi.model.mapper.IdtModelLayerMapper;
import com.guodi.model.mapper.MdlModelMapper;
import com.guodi.model.service.IIdModelLayerService;
import com.guodi.system.feign.ISysClient;
import com.guodi.system.vo.OrgVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @描述：指标、模型关联图层信息表 服务类
 * @作者: 汤厚韬
 * @日期: 2021-1-11
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class IdtModelLayerServiceImpl extends ServiceImpl<IdtModelLayerMapper, IdtModelLayer> implements IIdModelLayerService {

    @Resource
    MdlModelMapper mdlModelMapper;
    @Resource
    ISysClient sysClient;
    /**
     * @描述: 保存指标、模型关联图层数据
     * @入参:
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021/1/11
     */
    @Override
    public AjaxResult saveIdtModelLayerList(String saveJson, LoginUser bladeUser) {
        ApiIdtModelLayerDto apiIdtModelLayerDto = JSONObject.parseObject(saveJson, ApiIdtModelLayerDto.class);
        if (StringUtils.isBlank(apiIdtModelLayerDto.getParentId())) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "关联的指标或模型的主键不能为空");
        }
        if (apiIdtModelLayerDto.getLayerDtoList() == null || apiIdtModelLayerDto.getLayerDtoList().size() == 0 ) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "关联的图层主键不能为空");
        }
        if (apiIdtModelLayerDto.getIdtModelType() == null) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "关联的指标或模型类型不能为空");
        }

        List<String> layerIds = new ArrayList<>();
        for (LayerDto dto : apiIdtModelLayerDto.getLayerDtoList()) {
            layerIds.add(dto.getLayerId());
        }

        //验证当前目录下是否存在重名
        LambdaQueryWrapper<IdtModelLayer> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(IdtModelLayer::getParentId, apiIdtModelLayerDto.getParentId());
        queryWrapper.in(IdtModelLayer::getLayerId, layerIds);
        List<IdtModelLayer> list = super.list(queryWrapper);
        if(list.size() > 0){
            return new AjaxResult(StatusCode.ERROR_CODE_40005,"该节点下已存在名称为"+list.get(0).getLayerName()+"的图层，请更换！");
        }
        Integer maxSort = baseMapper.selectMaxSort(apiIdtModelLayerDto.getParentId());
        maxSort = maxSort == null ? 0 : maxSort;

        Integer sort = maxSort + 1;

        // 定义返回集合
        List<IdtIndicatorsDir> resultList = new ArrayList<>();

        //定义存储数据的集合
        List<IdtModelLayer> idtModelLayerList = new ArrayList<>();
        for(int i = 0; i < apiIdtModelLayerDto.getLayerDtoList().size(); i++){
            LayerDto layerDto = apiIdtModelLayerDto.getLayerDtoList().get(i);
            IdtModelLayer idtModelLayer = new IdtModelLayer();
            idtModelLayer.setId(UuidUtil.get32UUID());
            idtModelLayer.setLayerId(layerDto.getLayerId());
            idtModelLayer.setLayerName(layerDto.getName());
            idtModelLayer.setIdtModelType(apiIdtModelLayerDto.getIdtModelType());
            idtModelLayer.setSystemId(apiIdtModelLayerDto.getSystemId());
            idtModelLayer.setParentId(apiIdtModelLayerDto.getParentId());

            // 图层
            idtModelLayer.setDataType(1);
            idtModelLayer.setSort(sort);
            // 默认启用图层
            idtModelLayer.setIsUsing(0);
            // 默认透明度一百
            idtModelLayer.setLayerAlpha("100");
            // 设置别名
            idtModelLayer.setAlias(layerDto.getName());
            // 当前用户的行政区划编号
            String deptId = bladeUser.getDeptId();
            if (StringUtils.isNotBlank(deptId)) {
                String id = deptId.split(",")[0];
                R<OrgVO> r = sysClient.getOrg(Long.valueOf(id));
                if (r.isSuccess()) {
                    if (r.getData() != null && StringUtils.isNotBlank(r.getData().getRegionCode())) {
                        idtModelLayer.setDivisionCode(r.getData().getRegionCode());
                    }
                }
            }

            prepareData(idtModelLayer, true, bladeUser);
            sort++;
            idtModelLayerList.add(idtModelLayer);


            IdtIndicatorsDir idtIndicatorsDir = new IdtIndicatorsDir();
            idtIndicatorsDir.setId(idtModelLayer.getId());
            idtIndicatorsDir.setParentId(idtModelLayer.getParentId());
            idtIndicatorsDir.setName(idtModelLayer.getLayerName());
            idtIndicatorsDir.setAlias(idtModelLayer.getAlias());
            idtIndicatorsDir.setType(3);
            // 新增图层目录
            if (idtModelLayer.getDataType() == 0) {
                idtIndicatorsDir.setType(4);
            }
            idtIndicatorsDir.setSort(sort);
            idtIndicatorsDir.setIdtModelLayer(idtModelLayer);
            resultList.add(idtIndicatorsDir);
        }
        super.saveBatch(idtModelLayerList);
        return new AjaxResult(resultList);
    }

    /**
     * @描述: 更新保存指标、模型关联图层数据
     * @入参:
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021/1/11
     */
    @Override
    public AjaxResult updateIdtModelLayer(IdtModelLayer idtModelLayer, LoginUser bladeUser) {
        if (StringUtils.isBlank(idtModelLayer.getId())) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "主键不能为空");
        }
        /*if (StringUtils.isBlank(idtModelLayer.getParentId())) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "关联的指标或模型的主键不能为空");
        }
        if (StringUtils.isBlank(idtModelLayer.getLayerId())) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "关联的图层主键不能为空");
        }
        if (idtModelLayer.getDataType() == null) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "数据类型不能为空");
        }*/

        IdtModelLayer ysIdtModelLayer = super.getById(idtModelLayer.getId());

        LambdaQueryWrapper<IdtModelLayer> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(IdtModelLayer::getParentId, ysIdtModelLayer.getParentId());
        queryWrapper.eq(IdtModelLayer::getAlias, idtModelLayer.getAlias());
        queryWrapper.apply("id != {0}", idtModelLayer.getId());

        List<IdtModelLayer> list = super.list(queryWrapper);
        if (list.size() > 0) {
            for (IdtModelLayer idtModelLayer1 : list) {}
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该节点名称已经存在");
        }
        //获取原始数据

        ysIdtModelLayer.setAlias(idtModelLayer.getAlias());
        ysIdtModelLayer.setLayerAlpha(idtModelLayer.getLayerAlpha());
        ysIdtModelLayer.setIsUsing(idtModelLayer.getIsUsing());
        ysIdtModelLayer.setSort(idtModelLayer.getSort());
        ysIdtModelLayer.setModifier(bladeUser.getUserId().toString());
        ysIdtModelLayer.setModifyTime(new Date());
        ysIdtModelLayer.setDivisionCode(idtModelLayer.getDivisionCode());

        this.updateById(ysIdtModelLayer);

        IdtIndicatorsDir idtIndicatorsDir = new IdtIndicatorsDir();
        idtIndicatorsDir.setId(ysIdtModelLayer.getId());
        idtIndicatorsDir.setParentId(ysIdtModelLayer.getParentId());
        idtIndicatorsDir.setName(ysIdtModelLayer.getLayerName());
        idtIndicatorsDir.setType(3);
        idtIndicatorsDir.setAlias(idtModelLayer.getAlias());
        idtIndicatorsDir.setSort(idtModelLayer.getSort());
        idtIndicatorsDir.setIdtModelLayer(ysIdtModelLayer);

        return new AjaxResult(idtIndicatorsDir);
    }

    /**
     * @描述: 获取最多排序数
     * @入参:
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021/1/11
     */
    @Override
    public AjaxResult selectMaxSort(String parentId) {
        Integer maxSort = baseMapper.selectMaxSort(parentId);
        maxSort = maxSort == null ? 1 : maxSort + 1;
        return new AjaxResult(maxSort);
    }

    /**
     * @描述: 删除指标、模型关联图层数据
     * @入参: ids
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021/1/11
     */
    @Override
    public AjaxResult deleteIdtModelLayer(String ids) {
        if (StringUtils.isBlank(ids)) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "主键不能为空");
        }
        String[] id = ids.split(",");
        List<String> list = Arrays.asList(id);
        super.removeByIds(list);
        return new AjaxResult();
    }

    /**
     * @描述: 新增指标、模型关联图层目录
     * @入参:
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021/1/11
     */
    @Override
    public AjaxResult addRelDir(IdtModelLayer idtModelLayer, LoginUser bladeUser) {
        LambdaQueryWrapper<IdtModelLayer> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(IdtModelLayer::getParentId, idtModelLayer.getParentId());
        queryWrapper.eq(IdtModelLayer::getLayerName, idtModelLayer.getLayerName());
        queryWrapper.eq(IdtModelLayer::getSystemId, idtModelLayer.getSystemId());

        List<IdtModelLayer> list = super.list(queryWrapper);
        if (list.size() > 0) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该目录已经存在");
        }
        idtModelLayer.setId(UuidUtil.get32UUID());
        idtModelLayer.setDataType(0);
        idtModelLayer.setAlias(idtModelLayer.getLayerName());
        /*if (idtModelLayer.getSort() == null) {
            Integer maxSort = baseMapper.selectMaxSort(idtModelLayer.getParentId());
            maxSort = maxSort == null ? 1 : maxSort + 1;
            idtModelLayer.setSort(maxSort);
        }*/
        prepareData(idtModelLayer, true, bladeUser);
        saveOrUpdate(idtModelLayer);

        IdtIndicatorsDir idtIndicatorsDir = new IdtIndicatorsDir();
        idtIndicatorsDir.setId(idtModelLayer.getId());
        idtIndicatorsDir.setParentId(idtModelLayer.getParentId());
        idtIndicatorsDir.setName(idtModelLayer.getLayerName());
        idtIndicatorsDir.setType(4);
        idtIndicatorsDir.setAlias(idtModelLayer.getAlias());
        idtIndicatorsDir.setSort(idtModelLayer.getSort());
        return new AjaxResult(idtIndicatorsDir);
    }

    /**
     * @描述: 更新指标、模型关联图层目录
     * @入参:
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021/1/11
     */
    @Override
    public AjaxResult updateRelDir(IdtModelLayer idtModelLayer, LoginUser bladeUser) {
        LambdaQueryWrapper<IdtModelLayer> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(IdtModelLayer::getParentId, idtModelLayer.getParentId());
        queryWrapper.eq(IdtModelLayer::getLayerName, idtModelLayer.getLayerName());
        queryWrapper.eq(IdtModelLayer::getSystemId, idtModelLayer.getSystemId());
        queryWrapper.apply("id != {0}", idtModelLayer.getId());

        List<IdtModelLayer> list = super.list(queryWrapper);
        if (list.size() > 0) {
            return new AjaxResult(StatusCode.ERROR_CODE_40005, "该目录已经存在");
        }
        //获取原始数据
        IdtModelLayer ysIdtModelLayer = super.getById(idtModelLayer.getId());
        ysIdtModelLayer.setLayerName(idtModelLayer.getLayerName());
        ysIdtModelLayer.setSort(idtModelLayer.getSort());
        ysIdtModelLayer.setDataType(0);
        ysIdtModelLayer.setAlias(idtModelLayer.getLayerName());
        ysIdtModelLayer.setModifier(bladeUser.getUserId().toString());
        ysIdtModelLayer.setModifyTime(new Date());
        updateById(ysIdtModelLayer);

        IdtIndicatorsDir idtIndicatorsDir = new IdtIndicatorsDir();
        idtIndicatorsDir.setId(ysIdtModelLayer.getId());
        idtIndicatorsDir.setParentId(ysIdtModelLayer.getParentId());
        idtIndicatorsDir.setName(ysIdtModelLayer.getLayerName());
        idtIndicatorsDir.setType(4);
        idtIndicatorsDir.setAlias(idtModelLayer.getAlias());
        idtIndicatorsDir.setSort(idtModelLayer.getSort());
        return new AjaxResult(idtIndicatorsDir);
    }

    /**
     * @param id
     * @描述: 根据主键删除关联目录
     * @入参: id
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021-1-11
     */
    @Override
    public AjaxResult deleteRelDir(String id) {
        baseMapper.deleteRelDir(id);
        return new AjaxResult();
    }

    /**
     * @描述: 根据体型ID获取所有关联数据
     * @入参:
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021-1-11
     **/
    @Override
    public List<IdtModelLayer> getListBySystemId(String systemId) {
        LambdaQueryWrapper<IdtModelLayer> queryWrapper = new QueryWrapper().lambda();
        queryWrapper.eq(IdtModelLayer::getSystemId, systemId);
        return super.list(queryWrapper);
    }

    /**
     * @param parentId
     * @param year
     * @描述: 获取指标、模型关联图层列表
     * @入参:
     * @出参:
     * @作者: 汤厚韬
     * @日期: 2021-1-11
     */
    @Override
    public AjaxResult getRelLayerList(String parentId, String year, String divisionCode) {
        List<IdtModelLayerDto> list = null;
        // 模型关联图列表查询
        if (StringUtils.isNotBlank(year)) {
            LambdaQueryWrapper<IdtModelLayer> queryWrapper = new QueryWrapper().lambda();
            queryWrapper.eq(IdtModelLayer::getParentId, parentId);
            queryWrapper.eq(IdtModelLayer::getLayerName, year);
            IdtModelLayer yearDto = getOne(queryWrapper);
            if (yearDto != null && StringUtils.isNotBlank(yearDto.getId())) {
                list = baseMapper.getRelLayerList(yearDto.getId());
            }
        } else {
            // 指标关联图层列表查询
            list = baseMapper.getRelLayerList(parentId);
        }
        if (list != null && list.size() > 0){
            // 兼容行政区划多选
            if(StringUtils.isNotBlank(divisionCode)){
                list = list.stream().filter(x -> divisionCode.contains(x.getDivisionCode())).collect(Collectors.toList());
            }
            for (IdtModelLayerDto dto : list) {
                dto.setMapLayer(mdlModelMapper.listMapLayerByMapLayerId(dto.getLayerId()));
            }
        }
        return new AjaxResult(list);
    }


    private void prepareData(IdtModelLayer idtModelLayer, boolean isSave, LoginUser baseUser) {
        if (isSave) {
            idtModelLayer.setCreator(baseUser.getUserId().toString());
            idtModelLayer.setCreateTime(new Date());
            // 防止误修改
            idtModelLayer.setModifier(null);
            idtModelLayer.setModifyTime(null);
        } else {
            idtModelLayer.setModifier(baseUser.getUserId().toString());
            idtModelLayer.setModifyTime(new Date());
            // 防止误修改
            idtModelLayer.setCreator(null);
            idtModelLayer.setCreateTime(null);
        }
    }
}
